package websocket

import (
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
	"net/http"
	"twwch/k8s-admin/config"
	"twwch/k8s-admin/websocket/handler"
)

func echo(w http.ResponseWriter, r *http.Request) {
	// 完成和Client HTTP >>> WebSocket的协议升级
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		// 解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		// 接收客户端message
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		// 向客户端发送message
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}

func Run() {
	var wsProd = config.Get().WsPort
	fmt.Println("websocket start")
	var addr = flag.String("addr", wsProd, "http service address")
	http.HandleFunc("/ws/shell", handler.Pod.Shell)
	http.HandleFunc("/echo", echo)
	log.Fatal(http.ListenAndServe(*addr, nil))
}
